<template>
  <el-dialog v-bind="{ ...$attrs }" class="app-add" >
      <el-tabs type="card">
        <el-tab-pane label="新增用户">
          <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px"  status-icon>
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="ruleForm.userName" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="ruleForm.email" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="ruleForm.password"  />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
          <el-button  @click="$emit('close')"> 关闭 </el-button>
          <el-button  type="primary" @click="submitForm(ruleFormRef)"> 确认 </el-button>
      </template>
  </el-dialog>
</template>
 
<script lang="ts" setup>
import { reactive, ref ,defineEmits} from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { addUser } from '@/server/user'
import { ElMessage ,ElNotification } from 'element-plus'
//定义自定义事件
const emit = defineEmits<{(event: 'close'): void;(event: 'success'): void;  }>()
//定义属性
interface RuleForm {
  userName: string,
  email: string,
  password: string,
  shouldChangePasswordOnNextLogin:boolean,
  sendConfirmationEmail:boolean,
  isActive:boolean
}
//表单
const formSize = ref('large')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  userName: '',
  email: '',
  password:'',
  shouldChangePasswordOnNextLogin:false,
  sendConfirmationEmail:false,
  isActive:true
})

const rules = reactive<FormRules<RuleForm>>({
    userName:[{
      required:true,
      message:"请输入用户名"
    }],
    email:[{
      type:"email",
      required:true,
      message:"请输入邮箱"
    }],
    password:[{
      required:true,
      message:"请输入密码"
    }],
})
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate( async (valid, fields) => {
    if (valid) {
      console.log('submit!')
      try{
        await addUser(ruleForm)
        ElMessage.success("新增成功")
        emit('success')
        
      }catch(err:any){
        ElNotification({
          title: 'Error',
          message: err.error.message,
          type: 'error',
        })
      }
      
    } else {
      console.log('error submit!', fields)
    }
  })
}

</script>
<style lang="scss" scoped>
 .el-dialog{
  height: 500px !important;
  overflow: auto;
  // .el-tabs{
  //   height: 400px;
  //   overflow: auto;
  // }
}
</style>